package com.wnhz.work.yz.jpush;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MainActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.activity.BathroomDetailActivity;
import com.wnhz.work.yz.activity.BathroomGridActivity;
import com.wnhz.work.yz.activity.ChuFangDetialsActivity;
import com.wnhz.work.yz.activity.GroupActivity;
import com.wnhz.work.yz.activity.GroupDetailsActivity;
import com.wnhz.work.yz.activity.IndustryDetialsActivity;
import com.wnhz.work.yz.activity.IndustryFitmentActivity;
import com.wnhz.work.yz.activity.JobauditActivity;
import com.wnhz.work.yz.activity.LibraryActivity;
import com.wnhz.work.yz.activity.LookDetailsActivity;
import com.wnhz.work.yz.activity.OrderDetailsActivity;
import com.wnhz.work.yz.activity.ProjectDetailsActivity;
import com.wnhz.work.yz.activity.RecordsActivity;
import com.wnhz.work.yz.activity.ShoppingDetailsActivity;
import com.wnhz.work.yz.activity.TreasureActivity;
import com.wnhz.work.yz.activity.UnderMemberActivity;
import com.wnhz.work.yz.activity.VideoActivity;
import com.wnhz.work.yz.dialog.SimpleDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = "JPush";
    private static Map<String, String> map = new HashMap<>();
    private String type;
    private String pid;
    private Activity activity;
    private SimpleDialog dialog;

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        Log.e(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.e(TAG, "[MyReceiver] 接收Registration Id : " + regId);
            //send the Registration Id to your server...
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Log.e(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            processCustomMessage(context, bundle, intent);
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.e(TAG, "[MyReceiver] 接收到推送下来的通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            Log.e(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.e(TAG, "[MyReceiver] 用户点击打开了通知");
            String url = "https://www.baidu.com/";
            try {
                JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                url = json.optString("url");
                Log.e("极光推送====", url);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Log.e("点击后 == 接受到消息的", "");
            for (String key : map.keySet()) {//map.keySet()返回的是所有key的值
                if (key.equals("type")) {
                    type = map.get(key);
                    Log.e("点击后 == 接受到消息的 key值===", "" + key + "===type值=" + type);
                }

                if (key.equals("pid")) {
                    pid = map.get(key);
                    Log.e("点击后 == 接受到消息的 key值===", "" + key + "===pid值=" + pid);
                }
            }

            if (type.equals("0")) {
                //家居馆商品详情
                intent = new Intent(context, ShoppingDetailsActivity.class);
                intent.putExtra("goodsId", pid);
            } else if (type.equals("1")) {
                //浴室
                intent = new Intent(context, BathroomDetailActivity.class);
                intent.putExtra("packageId", pid);
            } else if (type.equals("2")) {
                //工业化
                intent = new Intent(context, IndustryDetialsActivity.class);
                intent.putExtra("goodsId", pid);
            } else if (type.equals("3")) {
                //厨房
                intent = new Intent(context, ChuFangDetialsActivity.class);
                intent.putExtra("goodsId", pid);
            } else if (type.equals("4")) {
                //家居馆订单
                intent = new Intent(context, OrderDetailsActivity.class);
                intent.putExtra("orderId", pid);
            } else if (type.equals("5")) {
                //项目订单
                intent = new Intent(context, ProjectDetailsActivity.class);
                intent.putExtra("budget_id", pid);

            } else if (type.equals("6")) {
                //浴室分类
                intent = new Intent(context, BathroomGridActivity.class);
                intent.putExtra("title", "");
                intent.putExtra("cateId", pid);

            } else if (type.equals("7")) {
                //文库
                intent = new Intent(context, LibraryActivity.class);

            } else if (type.equals("8")) {
                //视频
                intent = new Intent(context, VideoActivity.class);

            } else if (type.equals("9")) {
                //案例

            } else if (type.equals("10")) {
                //新闻

            } else if (type.equals("11")) {
                //特批
                intent = new Intent(context, JobauditActivity.class);
            } else if (type.equals("12")) {
                //备案
                intent = new Intent(context, LookDetailsActivity.class);
                intent.putExtra("recordid", pid);
            } else if (type.equals("13")) {
                //团队
                intent = new Intent(context, GroupDetailsActivity.class);
                intent.putExtra("teamId", pid);
            } else if (type.equals("14")) {
                //财富宝
                intent = new Intent(context, TreasureActivity.class);

            } else if (type.equals("15")) {
                //会员下单提成
                intent = new Intent(context, UnderMemberActivity.class);
            }


//        	//打开自定义的Activity
            intent.putExtras(bundle);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(intent);

        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Log.e(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Log.e(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
        } else {
            Log.e(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Log.e(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");

                        map.put(myKey, json.optString(myKey));
//						StringList.add(json.optString(myKey));
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    //send msg to MainActivity
    private void processCustomMessage(Context context, Bundle bundle, Intent intent) {
        Log.e("点击后 == 接受到消息======", "" + printBundle(bundle));
        for (String key : map.keySet()) {//map.keySet()返回的是所有key的值
            if (key.equals("type")) {
                type = map.get(key);
                Log.e("点击后 == 接受到消息的 key值===", "" + key + "===type值=" + type);
            }

            if (key.equals("pid")) {
                pid = map.get(key);
                Log.e("点击后 == 接受到消息的 key值===", "" + key + "===pid值=" + pid);
            }
        }

        if (type.equals("16")) {
               //打开自定义的Activity
//            intent.putExtras(bundle);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
//            context.startActivity(intent);
//            dialog = new SimpleDialog(context, "您的账号已在其它设备登录, 是否为本人操作", "知道了", "重新登录", new SimpleDialog.OnButtonClick() {
//                @Override
//                public void onNegBtnClick() {
//                    MyApplication.getInstance().exit(activity);
//                }
//
//                @Override
//                public void onPosBtnClick() {
//
//                }
//            });
//            dialog.setCanceledOnTouchOutside(false);
//            dialog.show();
            MyApplication.getInstance().userBean = null;
            MyApplication.getInstance().gotoLoginActivity();
        }

//		if (MainActivity.isForeground) {
//			String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
//			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
//			Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
//			msgIntent.putExtra(MainActivity.KEY_MESSAGE, message);
//			if (!TextUtils.isEmpty(extras)) {
//				try {
//					JSONObject extraJson = new JSONObject(extras);
//					if (extraJson.length() > 0) {
//						msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras);
//					}
//				} catch (JSONException e) {
//
//				}
//
//			}
//			context.sendBroadcast(msgIntent);
//		}
    }
}
